/*
 * @(#)AutoTaskStartSubWorkflowTemplate.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.workflow.action;


import java.sql.Connection;
import java.sql.SQLException;

import org.quartz.JobDataMap;

import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.ErrorConstant;
import com.dcivision.framework.EventLogger;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.Utility;
import com.dcivision.workflow.WorkflowErrorConstant;
import com.dcivision.workflow.bean.WorkflowProgress;
import com.dcivision.workflow.bean.WorkflowRecord;
import com.dcivision.workflow.core.AutomaticTaskInterface;
import com.dcivision.workflow.core.WorkflowProcessor;
import com.dcivision.workflow.core.WorkflowProgressManager;
import com.dcivision.workflow.web.MaintWorkflowRecordForm;

/**
 * This is a class that acts as a template for coding automatic task to trigger sub workflow
 *
 * @author Rollo Chan
 * @company DCIVision Limited
 * @creation date 01/11/2006
 * @version $Revision: 1.16 $
 */
public class AutoTaskStartSubWorkflowTemplate extends AbstractStartSubWorkflow implements AutomaticTaskInterface{

  public static final String REVISION                       = "$Revision: 1.16 $";

  public AutoTaskStartSubWorkflowTemplate() {
    this.numOfRoutine = 1;
    this.labelType = WorkflowProcessor.LABEL_TYPE_USER_DEFINE;
    this.labelString = new String[] { "workflow.label.step_status_G" };
    this.parameterNames=new String[]{"workflow.label.workflow_code"};////need parameter,if parameterNames is not null then searStaff button will display in the web
    this.bAutoExecuteNextStep = true;
    this.parentDependent = true;
    this.currentProgressStatus = WorkflowProgress.STATUS_PENDING;
    this.bAllowUploadParentAttachments = true;//allow upload all parent attachments to child progress

    //* depends on whether want the subworkflow to be running independent of the parent workflow or not
    /*//if want change the parentDependent,see bellow code
    if (this.parentDependent) {
      this.currentProgressStatus = WorkflowProgress.STATUS_PENDING; //* subworkflow has close relationship with parent
    } else {
      this.currentProgressStatus = WorkflowProgress.STATUS_GENERAL_ACCOMPLISHMENT; //* subflow running independent of the parnet workflow
    }*/
  }

  public synchronized void execute(JobDataMap dataMap, WorkflowProgress currentProgress) throws ApplicationException {
    log.info("***** AutoTaskStartSubWorkflowTemplate workflow processor BEGIN *****");
    Connection conn = null;
    SessionContainer sessionCon = null;

    Integer trigerEventUserID = new Integer(0);
    String serverName = "127.0.0.1";
    String functionName = SystemFunctionConstant.WORKFLOW_TASK;
    String errorMessage = "";

    try {
      // get the DB Connection
      conn = getConnection();
      // get the sessionContainer
      sessionCon = this.getSessionContainer();


      /*************************************************************
       *  get Event Log Information Begin
       *************************************************************/
      if (!Utility.isEmpty(sessionCon.getUserRecordID())) {
        trigerEventUserID = sessionCon.getUserRecordID();
      }

      if (!Utility.isEmpty(sessionCon.getUserIPAddress())) {
        serverName = sessionCon.getUserIPAddress();
      }
      errorMessage = " Track ID: " + currentProgress.getTrackID() + ", Workflow Progress ID : " + currentProgress.getID() + ", Workflow Step ID: " + currentProgress.getWorkflowStepID() + "<br> ";

      /*************************************************************
       *  get Event Log Information End
       *************************************************************/

      //create the DAOs
      WorkflowProgressManager progressManager = new WorkflowProgressManager(sessionCon, conn);

      //get the SubWorkflowRecord
      WorkflowRecord workflowRecord = this.getSubWorkflowRecord(sessionCon, conn, currentProgress.getWorkflowStepID());

      //set the Form
      MaintWorkflowRecordForm recordForm = new MaintWorkflowRecordForm();
      recordForm.setFormData(workflowRecord);

      //set the sessionContainer,If not set the sessionContainer,can not start the subWorkflow
      setSessionContainer(sessionCon,conn,currentProgress);

      //do your business before start subworkflow
      doLocalBussinessBeforeStartSubWorkflow();

      //start the subWorkflow
      log.debug("start workflow start new track");
      WorkflowProgress workflowProgress = (WorkflowProgress) progressManager.startWorkflowTrack(recordForm);
      log.debug("end workflow start new track");

      if (bAllowUploadParentAttachments) {
        setSubWorkFlowAttachmentsFromParentProgress(sessionCon,conn,workflowProgress, currentProgress);
      }

      if (this.parentDependent) {
        setChildParentProgressShip(sessionCon, conn, currentProgress, workflowProgress);
      }

      //do your business after start subworkflow
      doLocalBussinessAfterStartSubWorkflow();

      //* after the execution, set the desired appropriate out number
      this.returnRoutineIndex = 1; //* should be between 0 and numOfRoutine-1
      //* if need to auto-Execute the following step, set the below variable to true (default false)
      this.bAutoExecuteNextStep = false;
      this.bCreateNextWorkflowProgress = true;
      // commit the conn
      this.commitConnection(conn);
    } catch (ApplicationException appEx) {
      log.error("Application exception:\n" + appEx);
      /***********************************
       *  Record the Event Log.
       ***********************************/
      EventLogger.logEventMessage(trigerEventUserID, serverName, errorMessage, appEx.getMsgCode(), WorkflowErrorConstant.LOG_AUTO_TASK_ERROR_CODE, functionName, appEx.toString());
      try {
        this.rollbackConnection(conn);//rollback the conn
      } catch (SQLException roolbackE) { }
      throw appEx; //* prop
    } catch (Exception e) {
      log.error("Error during processing this automatic task.", e);
      /***********************************
       *  Record the Event Log.
       ***********************************/
      EventLogger.logEventMessage(trigerEventUserID, serverName, errorMessage, ErrorConstant.COMMON_FATAL_ERROR, WorkflowErrorConstant.LOG_AUTO_TASK_ERROR_CODE, functionName, e.toString());
      try {
        this.rollbackConnection(conn);//rollback the conn
      } catch (SQLException roolbackE) { }
      throw new ApplicationException(ErrorConstant.COMMON_FATAL_ERROR); //* throw an applicationExcpetion with an appropriate
    } finally {
      //close the connection
      this.closeConnection(conn);
    }

    log.info("***** AutoTaskStartSubWorkflowTemplate workflow processor END   *****");
  }

  private void doLocalBussinessBeforeStartSubWorkflow(){
    //do something before start subworkflow
    //add your code here
  }
  private void doLocalBussinessAfterStartSubWorkflow(){
    //do something after start subworkflow
    //add your code here
  }

  public WorkflowProcessor getWorkflowProgress() {
   return this;//return self
  }

}
